# #!/user/bin/env python3
# # -*- coding: utf-8 -*-
#
# # -*- coding: utf-8 -*-#
from concurrent.futures import ThreadPoolExecutor
from datetime import timedelta

import requests
from flask import Flask

# import detect
from utils.datasets import *

## app

Image.MAX_IMAGE_PIXELS = None

set_upload_path = 'data/images'
set_result_path = 'data/images'
ALLOWED_EXTENSIONS = {'png', 'jpg', 'JPG', 'PNG', 'bmp', 'mp4', 'MOV'}


def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1] in ALLOWED_EXTENSIONS

app = Flask(__name__)
app.send_file_max_age_default = timedelta(seconds=1)

exector = ThreadPoolExecutor(8)


# # URL地址 识别检测
# @app.route('/api/face_detection5', methods=['POST', 'GET'])
# def upload():
#     if request.method == 'POST':
#         files = request.files.getlist('file')
#         for file in files:
#             # todo 如何创建线程池 并行识别 做得到吗?
#             print("xx")
#             mutiRead(file)
#             # lab, loc, res = detect.main(opt)
#         # 检测结果写到的目录
#         # cv2.imwrite(os.path.join(basepath, set_result_path, filename_+'_res.jpg'), img)
#         # print(res)
#         # return res
#     return render_template('upload.html')


# 多文件识别
# def mutiRead(f):
#     if not (f and allowed_file(f.filename)):
#         return jsonify({"error": 1001, "msg": "File type exception !"})
#     t = f.filename
#     basepath = os.path.dirname(__file__)
#     # 文件上传目录地址
#     upload_path = os.path.join(basepath, set_upload_path, secure_filename(f.filename))
#     f.save(upload_path)
#     with torch.no_grad():
#         opt = detect.parse_opt(upload_path)
#         detect.main(opt)


# # 封装数据 并发送post请求 object 检测到的物体名称 ,importPath 生成的图片路径
def encapsulationDataObject(importPath, object):
    url = 'http://localhost:8081/insertData'
    files = {'file': (open(importPath, 'rb'))}
    result = jsonData(object)
    data = {'data': json.dumps(result, ensure_ascii=False)}
    resp = requests.post(url, files=files, data=data)
    print(resp.text)

# 集合转列表
def jsonData(obj):
    if isinstance(obj, set):
        return list(obj)
        raise TypeError


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5001, threaded=True)
